layui.use('form', function(){
	var form = layui.form;

	init();
	
});

//初始化标签
function init(){
	var labelIds = $("#labelIds").val();
	$.ajax({
		type: 'post',
		url: '/base/label/getAllLabel',
		dataType: 'json',
		success: function(result){
			var code = result.code;
			var html = '';
			if(code==0){
				var data = result.data;
				var html = '<div class="layui-row">';
				for(var i=0;i<data.length;i++){
					var map = data[i];
					var id = map.id;
					var labelType = map.labelType;
					
					var checkedHtml = '';//是否被选中
					if(labelIds.indexOf(id)>=0){
						checkedHtml = 'checked';
					}
					
					html += '<div class="layui-col-xs3 layui-col-sm3 layui-col-md3">';
					html += '<input type="checkbox" lay-skin="primary" name="labelType" ';
					html += ' title="' + labelType + '"' + checkedHtml + ' value="' + id + '">';
					html += '</div>';
					
					if((i+1)%4==0){
						html += '</div>';
						html += '<div class="layui-row">';
					}
					
				}
				html += '</div>';
				$("#labelsDiv").append(html);
				layui.form.render();
			}
		},
		error: function(e){
			layui.layer.msg('网络异常', {icon: 5});
		}
	});	
}

//保存
function save(){
	var arr = [];
	
	var id = $("#id").val();
	
	var inputs = $("input[name='labelType']:checked");
	for(var i=0;i<inputs.length;i++){
		var labelId = $(inputs[i]).val();
		var map = {
			'articleId': id,
			'labelId' : labelId
		};
		arr[i] = map;
	}
	
	$.ajax({
		type: 'post',
		url: '/base/article/saveLabels',
		contentType : "application/json",
		dataType: 'json',
		data: JSON.stringify(arr),
		success: function(result){
			console.log(result);
			var code = result.code;
			if(code==0){
				layui.layer.msg('保存成功', {icon: 6},function(){
					toBack();//刷新表格
				});
			}else{
				layui.layer.msg('保存失败', {icon: 5});
			}
		},
		error: function(e){
			layui.layer.msg('网络异常', {icon: 5});
		}
	});
}

//返回
function toBack(){
	var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
	parent.layer.close(index); //再执行关闭  
}